<?php

namespace app\agent\model;

use think\facade\Db;

class Recharge
{
    /**
     * 列表.
     */
    public function getList($params)
    {
        $where = [];
        $where[] = ['agent_id', '=', $params['agent']['id']];
        $where[] = ['type', 'in', [BALANCE_AGENT_RECHARGE, BALANCE_ONLINE_RECHARGE]];
        $paginate = [
            'page' => $params['page'] ?? 1,
            'list_rows' => $params['list_rows'] ?? 10,
        ];
        $createdDate = $params['createdDate'] ?? [];
        if (is_array($createdDate) && !empty($createdDate[0]) && $createdDate[1]) {
            $where[] = ['created_at', 'between time', [$createdDate[0], $createdDate[1].' 23:59:59']];
        }
        $list = Db::name('agent_balance_log')
            ->where($where)
            ->order('id desc')
            ->paginate($paginate)
            ->toArray();
        foreach ($list['data'] as $k => $v) {
            $list['data'][$k]['amount'] = fen2yuan($v['amount']);
            unset($list['data'][$k]['agent_id']);
        }
        $list['balance'] = fen2yuan($params['agent']['balance']);

        return success('操作成功', $list);
    }

    /**
     * 添加.
     */
    public function create($params)
    {
        // 支付通道要收 0.6% 的手续费，所以不做在线充值了
        exit;
        $amount = trim($params['amount']);
        $amount = floatval($amount);
        if ($amount < 0.01) {
            return fail('充值金额有误');
        }
        if ($amount > 1000000) {
            return fail('充值金额不能大于 100 万');
        }

        $orderId = $this->generateOrderId();
        if (false === $orderId) {
            return fail('订单号生成失败，请重试');
        }
        $amount = yuan2fen($params['amount']);
        $payLog = [
            'agent_id' => $params['agent']['id'],
            'pay_channel' => 'alipay' == $params['pay_type'] ? 2 : 1,
            'order_id' => $orderId,
            'trade_type' => 'SCAN',
            'amount' => $amount,
            'sale_price' => $amount,
            'status' => 1,
            'remark' => 'alipay' == $params['pay_type'] ? '支付宝充值' : '微信充值',
            'type' => 2,
        ];
        Db::startTrans();
        try {
            $id = Db::name('pay_log')
                ->insertGetId($payLog);
            $payLog['id'] = $id;
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return fail('订单生成失败，请重试：'.$e->getMessage());
        }

        try {
            $payType = ucfirst($params['pay_type']);
            $payType = "\\app\\common\\model\\$payType";
            $model = new $payType();

            return $model->web([
                'order_id' => $payLog['order_id'],
                'agent_id' => $params['agent']['id'],
                'amount' => $amount,
                'name' => '话费系统充值 '.$params['amount'].' 元',
            ]);
            // 扫码支付
            // return $model->scan([
            //     'order_id' => $payLog['order_id'],
            //     'agent_id' => $params['agent']['id'],
            //     'amount' => $amount,
            //     'name' => '话费系统充值 ' . $params['amount'] . ' 元',
            // ]);
        } catch (\Exception $e) {
            return fail('支付链接生成失败：'.$e->getMessage());
        }
    }

    private function generateOrderId()
    {
        for ($i = 0; $i < 21; ++$i) {
            $orderId = date('ymdHis').str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);
            $id = Db::name('pay_log')
                ->where('order_id', $orderId)
                ->value('id');
            if (empty($id)) {
                return $orderId;
            }
        }

        return false;
    }

    /**
     * 充值成功回调.
     */
    public function handleSuccess($payLog)
    {
        // 支付通道要收 0.6% 的手续费，所以不做在线充值了
        exit;
        Db::name('pay_log')
            ->where('id', $payLog['id'])
            ->update([
                'status' => 2,
                'trade_no' => $payLog['trade_no'],
            ]);
        $balance = Db::name('agent')
            ->where('id', $payLog['agent_id'])
            ->lock(true)
            ->value('balance');
        Db::name('agent_balance_log')
            ->insert([
                'agent_id' => $payLog['agent_id'],
                'type' => BALANCE_ONLINE_RECHARGE,
                'amount' => $payLog['amount'],
                'old_balance' => $balance,
                'new_balance' => $balance + $payLog['amount'],
                'remark' => (1 == $payLog['pay_channel'] ? '微信' : '支付宝').'充值 '.fen2yuan($payLog['amount']).' 元',
                'quote_id' => $payLog['id'],
            ]);
        Db::name('agent')
            ->where('id', $payLog['agent_id'])
            ->inc('balance', $payLog['amount'])
            ->inc('recharge_amount', $payLog['amount'])
            ->update([
                'balance_last_updated_at' => date('Y-m-d H:i:s'),
            ]);
    }

    /**
     * 支付宝扫码支付【固定收款码】.
     */
    public function queryOrderByTradeNo($params)
    {
        exit;
        // 已经后台给用户打款了，过滤掉
        if ($params['trade_no'] == '2021111922001422515725637321') {
            return fail('交易已存在');
        }

        $id = Db::name('agent_balance_log')
            ->where('trade_no', $params['trade_no'])
            ->value('id');
        if ($id) {
            return fail('交易已经存在');
        }

        try {
            $pay = new \app\common\model\Alipay();
            $res = $pay->findByTradeNo($params['trade_no']);
            if (false === $res) {
                return fail('交易不存在');
            }
        } catch (\Exception $e) {
            return fail('查询失败：'.$e->getMessage());
        }

        if (!isset($res['trade_status']) || !in_array($res['trade_status'], ['TRADE_SUCCESS', 'TRADE_FINISHED'])) {
            return fail('交易不存在。');
        }
        $amount = yuan2fen($res['total_amount']);

        $lockKey = 'agent.model.recharge.query_order_by_trade_no.' . $params['trade_no'];
        $lockVal = cache($lockKey);
        if ($lockVal) {
            return fail('操作频繁');
        }
        cache($lockKey, 1, 500);

        Db::startTrans();
        try {
            $balance = Db::name('agent')
                ->where('id', $params['agent']['id'])
                ->value('balance');
            Db::name('agent_balance_log')
                ->insert([
                    'agent_id' => $params['agent']['id'],
                    'type' => BALANCE_ONLINE_RECHARGE,
                    'amount' => $amount,
                    'old_balance' => $balance,
                    'new_balance' => $balance + $amount,
                    'remark' => '支付宝扫码充值 '.$res['total_amount'].' 元。支付宝订单号：'.$res['trade_no'],
                    'quote_id' => 0,
                    'trade_no' => $res['trade_no'],
                ]);
            Db::name('agent')
                ->where('id', $params['agent']['id'])
                ->inc('balance', $amount)
                ->inc('recharge_amount', $amount)
                ->update([
                    'balance_last_updated_at' => date('Y-m-d H:i:s'),
                ]);

            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();

            return fail('查询失败：'.$e->getMessage());
        }

        return success('充值成功');
    }

    /**
     * 支付宝扫码支付【呆萌价收款码】.
     */
    public function queryDmjOrderByTradeNo($params)
    {
        exit;
        $id = Db::name('agent_balance_log')
            ->where('trade_no', $params['trade_no'])
            ->value('id');
        if ($id) {
            return fail('交易已经存在');
        }

        // 调呆萌价接口，如果已经在呆萌价充值过，不再让充值
        // if (isProd()) {
        $url = 'http://www.shop.dmjvip.com/web-dmhw/huiRecharge/query?remark='.$params['trade_no'];
        // } else {
        //     $url = 'http://wx.mi.dmjvip.com//web-dmhw/huiRecharge/query?remark='.$params['trade_no'];
        // }
        $res = curlGet($url);
        $res = json_decode($res, true);
        if (!isset($res['result']) || $res['result'] != 1) {
            return fail($res['msgstr'] ?? '交易不存在');
        }

        if (empty($res['payTime'])) {
            return fail('交易时间有误');
        }
        if (empty($res['amount'])) {
            return fail('交易金额有误');
        }

        // 交易时间判断，早于上线时间的，不给用: 2021-10-22 14:30:00
        // $time = '2021-10-22 14:30:00';
        $time = '2021-11-09 13:45:00';
        if ($res['payTime'] < $time) {
            return fail('该笔交易无法在线充值，请联系商务充值');
        }

        // 交易金额
        $amount = yuan2fen($res['amount']);

        $lockKey = 'agent.model.recharge.query_dmj_order_by_trade_no.' . $params['trade_no'];
        $lockVal = cache($lockKey);
        if ($lockVal) {
            return fail('操作频繁');
        }
        cache($lockKey, 1, 500);

        // try {
        //     $pay = new \app\common\model\Alipay();
        //     $res = $pay->findByTradeNo($params['trade_no']);
        //     if (false === $res) {
        //         return fail('交易不存在');
        //     }
        // } catch (\Exception $e) {
        //     return fail('查询失败：'.$e->getMessage());
        // }

        // if (!isset($res['trade_status']) || !in_array($res['trade_status'], ['TRADE_SUCCESS', 'TRADE_FINISHED'])) {
        //     return fail('交易不存在。');
        // }
        // $amount = yuan2fen($res['total_amount']);

        Db::startTrans();
        try {
            $balance = Db::name('agent')
                ->where('id', $params['agent']['id'])
                ->value('balance');
            Db::name('agent_balance_log')
                ->insert([
                    'agent_id' => $params['agent']['id'],
                    'type' => BALANCE_ONLINE_RECHARGE,
                    'amount' => $amount,
                    'old_balance' => $balance,
                    'new_balance' => $balance + $amount,
                    'remark' => '【呆萌价】支付宝扫码充值 '.$res['amount'].' 元。支付宝订单号：'.$params['trade_no'],
                    'quote_id' => 1,
                    'trade_no' => $params['trade_no'],
                ]);
            Db::name('agent')
                ->where('id', $params['agent']['id'])
                ->inc('balance', $amount)
                ->inc('recharge_amount', $amount)
                ->update([
                    'balance_last_updated_at' => date('Y-m-d H:i:s'),
                ]);

            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();

            return fail('查询失败：'.$e->getMessage());
        }

        return success('充值成功');
    }
}
